import http from '@/utils/http'
import { isLoggedIn } from '@/utils/auth'
import drawAudioWave from '@/utils/drawAudioWave'
import { ElMessage } from 'element-plus'
import KeyboardAudio from '../utils/keyboardAudio.js'

export const textStudyMixin = {
  data() {
    return {
      loggedIn: false,
      loading: true,
      currentSentenceIndex: 0,
      currentWave: null,
      isPlaying: false,
      // 添加新的控制选项
      continuousReading: true,
      repeatSentence: false,
      repeatArticle: false,
      onlyReadUnMarked: false,
      sentenceRepeatCount: 1,
      currentSentencePlayCount: 0,
      sentenceEndTime: 0,
      // Store state when playing a single sentence
      wasPlaying: false,
      // 生词列表
      markedWords: [],
      // 句子掌握状态
      masteredSentences: []
    }
  },

  watch: {
    continuousReading() {
      this.writeOptsToLocalStorage()
    },
    repeatSentence() {
      this.writeOptsToLocalStorage()
    },
    repeatArticle() {
      this.writeOptsToLocalStorage()
    },
    sentenceRepeatCount() {
      this.writeOptsToLocalStorage()
    },
    onlyReadUnMarked() {
      this.writeOptsToLocalStorage()
    }
  },

  async mounted() {
    KeyboardAudio.register('Enter', this.togglePlayback)
    // 注册空格键
    KeyboardAudio.register(' ', this.togglePlayback)
    KeyboardAudio.register('ArrowLeft', this.playPrevious)
    KeyboardAudio.register('ArrowRight', this.playNext)
    this.getOptsFromLocalStorage()
    const lessonId = this.$route.params.id
    await this.loadLesson(lessonId)

    this.loadMarkedWordsFromServer()
    this.loggedIn = isLoggedIn()
    // 加载句子掌握状态
    if (this.loggedIn) {
      await this.loadSentenceProgress()
    }
    this.loading = false
  },

  beforeUnmount() {
    KeyboardAudio.destroy()
    if (this.audio) {
      this.audio.pause()
      this.audio = null
    }
  },

  methods: {
    getOptsFromLocalStorage() {
      const opts = localStorage.getItem('textStudyOpts')
      if (opts) {
        const parsedOpts = JSON.parse(opts)
        this.continuousReading = parsedOpts.continuousReading
        this.repeatSentence = parsedOpts.repeatSentence
        this.repeatArticle = parsedOpts.repeatArticle
        this.sentenceRepeatCount = parsedOpts.sentenceRepeatCount
        this.onlyReadUnMarked = parsedOpts.onlyReadUnMarked
      }
    },

    writeOptsToLocalStorage() {
      localStorage.setItem(
        'textStudyOpts',
        JSON.stringify({
          continuousReading: this.continuousReading,
          repeatSentence: this.repeatSentence,
          repeatArticle: this.repeatArticle,
          sentenceRepeatCount: this.sentenceRepeatCount,
          onlyReadUnMarked: this.onlyReadUnMarked
        })
      )
    },

    playPrevious() {
      if (this.currentSentenceIndex > 0) {
        this.currentSentenceIndex--
        // 如果启用了只读未掌握句子且当前句子已掌握，则继续向前查找
        if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
          while (this.currentSentenceIndex > 0 && this.masteredSentences.includes(this.currentSentenceIndex)) {
            this.currentSentenceIndex--
          }
          // 如果所有前面的句子都已掌握，则不执行任何操作
          if (this.masteredSentences.includes(this.currentSentenceIndex)) {
            return
          }
        }
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      }
    },

    togglePlayback() {
      if (this.isPlaying) {
        this.pauseAudio()
      } else {
        this.currentSentencePlayCount = 0 // 用户主动播放，重置计数
        this.playCurrentSentence()
      }
    },

    playNext() {
      if (this.currentSentenceIndex < this.lesson.content.length - 1) {
        this.currentSentenceIndex++
        // 如果启用了只读未掌握句子且当前句子已掌握，则继续向后查找
        if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
          while (
            this.currentSentenceIndex < this.lesson.content.length - 1 &&
            this.masteredSentences.includes(this.currentSentenceIndex)
          ) {
            this.currentSentenceIndex++
          }
          // 如果所有后面的句子都已掌握，则检查是否循环播放文章
          if (this.masteredSentences.includes(this.currentSentenceIndex)) {
            if (this.repeatArticle) {
              // 如果启用循环播放文章，则回到第一句
              this.currentSentenceIndex = 0
              // 如果第一句也已掌握，则继续向后查找未掌握的句子
              if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
                while (
                  this.currentSentenceIndex < this.lesson.content.length - 1 &&
                  this.masteredSentences.includes(this.currentSentenceIndex)
                ) {
                  this.currentSentenceIndex++
                }
                // 如果所有句子都已掌握，则不执行任何操作
                if (this.masteredSentences.includes(this.currentSentenceIndex)) {
                  return
                }
              }
            } else {
              return
            }
          }
        }
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      } else if (this.repeatArticle) {
        // 如果启用循环播放文章，则回到第一句
        this.currentSentenceIndex = 0
        // 如果启用了只读未掌握句子且第一句已掌握，则继续向后查找
        if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
          while (
            this.currentSentenceIndex < this.lesson.content.length - 1 &&
            this.masteredSentences.includes(this.currentSentenceIndex)
          ) {
            this.currentSentenceIndex++
          }
          // 如果所有句子都已掌握，则不执行任何操作
          if (this.masteredSentences.includes(this.currentSentenceIndex)) {
            return
          }
        }
        this.currentSentencePlayCount = 0 // 用户主动切换，重置计数
        this.playCurrentSentence()
      }
    },

    playCurrentSentence() {
      if (!this.audio || this.lesson.content.length === 0) return
      const sentence = this.lesson.content[this.currentSentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.drawWaveform(this.audio, sentence.startTime, sentence.endTime)
        this.audio.currentTime = sentence.startTime
        this.sentenceEndTime = sentence.endTime
        this.audio.play()
        this.isPlaying = true
      }
    },

    pauseAudio() {
      if (this.audio) {
        this.audio.pause()
      }
      this.isPlaying = false
    },

    onAudioTimeUpdate() {
      // 检查是否到达句子结束时间
      if (this.isPlaying && this.audio && this.audio.currentTime >= this.sentenceEndTime) {
        this.audio.pause()
        this.isPlaying = false
        this.onAudioEnded()
      }
    },

    onAudioEnded() {
      this.isPlaying = false
      if (this.repeatSentence && !this.continuousReading) {
        this.$nextTick(() => {
          this.playCurrentSentence()
        })
        return
      }

      // 如果启用了句子重复播放，或者启用了连续阅读并且设置了句子重复次数大于1
      if (
        (this.repeatSentence || (this.continuousReading && this.sentenceRepeatCount > 1)) &&
        this.currentSentencePlayCount < this.sentenceRepeatCount - 1
      ) {
        this.currentSentencePlayCount++
        this.$nextTick(() => {
          this.playCurrentSentence()
        })
        return
      }

      // 重置句子播放计数
      this.currentSentencePlayCount = 0

      // 如果启用连续阅读或到达文章末尾且启用了循环播放
      if (this.continuousReading || this.repeatArticle) {
        if (this.currentSentenceIndex < this.lesson.content.length - 1) {
          this.currentSentenceIndex++
          // 如果启用了只读未掌握句子且当前句子已掌握，则继续向后查找
          if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
            while (
              this.currentSentenceIndex < this.lesson.content.length - 1 &&
              this.masteredSentences.includes(this.currentSentenceIndex)
            ) {
              this.currentSentenceIndex++
            }
            // 如果所有后面的句子都已掌握，则检查是否循环播放文章
            if (this.masteredSentences.includes(this.currentSentenceIndex)) {
              if (this.repeatArticle) {
                // 如果启用循环播放文章，则回到第一句
                this.currentSentenceIndex = 0
                // 如果启用了只读未掌握句子且第一句已掌握，则继续向后查找
                if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
                  while (
                    this.currentSentenceIndex < this.lesson.content.length - 1 &&
                    this.masteredSentences.includes(this.currentSentenceIndex)
                  ) {
                    this.currentSentenceIndex++
                  }
                  // 如果所有句子都已掌握，则暂停播放
                  if (this.masteredSentences.includes(this.currentSentenceIndex)) {
                    return
                  }
                }
              } else {
                return
              }
            }
          }
          this.$nextTick(() => {
            this.playCurrentSentence()
          })
        } else if (this.repeatArticle) {
          // 如果启用循环播放文章，则回到第一句
          this.currentSentenceIndex = 0
          // 如果启用了只读未掌握句子且第一句已掌握，则继续向后查找
          if (this.onlyReadUnMarked && this.masteredSentences.includes(this.currentSentenceIndex)) {
            while (
              this.currentSentenceIndex < this.lesson.content.length - 1 &&
              this.masteredSentences.includes(this.currentSentenceIndex)
            ) {
              this.currentSentenceIndex++
            }
            // 如果所有句子都已掌握，则暂停播放
            if (this.masteredSentences.includes(this.currentSentenceIndex)) {
              return
            }
          }
          this.$nextTick(() => {
            this.playCurrentSentence()
          })
        }
      }
      // 如果不连续阅读且不循环文章，在句子结束时停止
      else if (!this.continuousReading && !this.repeatArticle) {
        // 保持在当前句子，等待用户操作
      }
    },

    changeSpeed(speed) {
      if (this.audio) {
        this.audio.playbackRate = speed
      }
    },

    // 连续阅读选项改变时的处理
    onContinuousReadingChange(value) {
      if (value) {
        // 启用连续阅读时，禁用句子循环播放
        this.repeatSentence = false
      }
    },

    // Play a single sentence when the button is clicked
    playSingleSentence(sentenceIndex) {
      // Store the current playback state
      this.wasPlaying = this.isPlaying

      // Pause current playback if playing
      if (this.isPlaying) {
        this.pauseAudio()
      }

      // Highlight the sentence being played
      this.currentSentenceIndex = sentenceIndex

      // Play the selected sentence
      this.playSentenceOnce(sentenceIndex)
    },

    // 切换单词标记状态（标记/取消标记为生词）
    async toggleWordMark(wordDetail) {
      // 创建一个包含原始单词信息的对象
      const markedWord = { ...wordDetail }
      let originalWord = null
      if (markedWord.originalWord && markedWord.originalWord.toLowerCase() !== markedWord.word) {
        originalWord = markedWord.originalWord
      }

      const index = this.markedWords.findIndex((word) => word.word === markedWord.word)

      try {
        if (index === -1) {
          // 添加到生词列表
          // this.markedWords.push(markedWord);
          this.markedWords = [...this.markedWords, markedWord]
          if (originalWord) {
            this.markedWords.push({
              word: originalWord
            })
          }
          // 同步到服务器，标记为收藏
          await this.syncVocabularyStatus(markedWord.word, false)
          ElMessage.success(`已将 "${markedWord.word}" 添加到生词本`)
        } else {
          // 从生词列表中移除
          this.markedWords = this.markedWords.filter((_, i) => i !== index)
          if (originalWord) {
            for (let i = 0; i < this.markedWords.length; i++) {
              if (this.markedWords[i].word === originalWord) {
                this.markedWords.splice(i, 1)
                break
              }
            }
          }
          // 同步到服务器，取消收藏
          await this.syncVocabularyStatus(markedWord.word, true)
          ElMessage.success(`已将 "${markedWord.word}" 从生词本移除`)
        }
      } catch (error) {
        console.error('Failed to update vocabulary status:', error)
        ElMessage.error('更新生词状态失败，请检查网络连接')
        // 操作失败时恢复原状
        if (index === -1) {
          // 添加失败，从列表移除
          this.markedWords.pop()
        } else {
          // 删除失败，恢复到列表
          this.markedWords.splice(index, 0, markedWord)
        }
      }
    },

    // 同步词汇状态到服务器
    async syncVocabularyStatus(word, isFavorite) {
      await http.post('/vocabulary/user', {
        word: word,
        is_favorite: isFavorite,
        is_learned: isFavorite,
        times_encountered: 1,
        times_practiced: 0
      })
    },

    // 从服务器加载用户的生词列表
    async loadMarkedWordsFromServer() {
      try {
        if (!isLoggedIn()) return
        const response = await http.get(`/vocabulary/difficult-words/${this.lesson.courseId}/${this.lesson.id}`)
        // 将服务器返回的生词转换为与本地数据结构一致的格式
        const serverMarkedWords = response.map((item) => ({
          word: item.vocabulary
        }))

        const mergedWords = [...serverMarkedWords]

        this.markedWords = mergedWords
      } catch (error) {
        console.error('Failed to load marked words from server:', error)
      }
    },

    isLargeScreen() {
      return window.innerWidth >= 768
    },

    drawWaveform(audio, startTime, endTime) {
      if (!this.isLargeScreen()) {
        return
      }
      this.currentWave = null
      drawAudioWave(audio, startTime, endTime, (d) => {
        this.currentWave = d
      })
    },

    // Play a sentence once and then restore previous state
    playSentenceOnce(sentenceIndex) {
      if (!this.audio || !this.lesson.content[sentenceIndex]) return
      const sentence = this.lesson.content[sentenceIndex]
      if (sentence.startTime !== undefined && sentence.endTime !== undefined) {
        this.drawWaveform(this.audio, sentence.startTime, sentence.endTime)
        const duration = sentence.endTime - sentence.startTime

        this.audio.currentTime = sentence.startTime
        this.audio.play()

        // Stop after the sentence duration
        setTimeout(() => {
          this.audio.pause()

          // Resume previous playback if it was playing
          if (this.wasPlaying) {
            this.playCurrentSentence()
          }
        }, (duration * 1000) / (this.audio.playbackRate || 1))
      }
    },

    // 切换句子掌握状态
    async toggleSentenceMastered(sentenceIndex) {
      try {
        // 检查必要的参数是否存在
        if (!this.lesson || !this.lesson.id || !this.lesson.courseId) {
          console.warn('Lesson ID or Course ID is not available')
          return
        }

        const isCurrentlyMastered = this.masteredSentences.includes(sentenceIndex)

        // 更新本地状态
        if (isCurrentlyMastered) {
          // 从掌握列表中移除
          this.masteredSentences = this.masteredSentences.filter((index) => index !== sentenceIndex)
        } else {
          // 添加到掌握列表
          this.masteredSentences = [...this.masteredSentences, sentenceIndex]
        }
        if (!isCurrentlyMastered) {
          KeyboardAudio.play('correct')
        }
        // 发送到服务器更新进度
        await http.post('/progress/sentences', {
          sentence_id: sentenceIndex,
          lesson_id: this.lesson.id,
          course_id: this.lesson.courseId,
          is_mastered: !isCurrentlyMastered,
          times_practiced: 1
        })
      } catch (err) {
        console.error('Failed to update sentence progress:', err)
        this.$message.error('更新句子掌握状态失败')

        // 出错时恢复原状态
        const isCurrentlyMastered = this.masteredSentences.includes(sentenceIndex)
        if (isCurrentlyMastered) {
          this.masteredSentences = this.masteredSentences.filter((index) => index !== sentenceIndex)
        } else {
          this.masteredSentences = [...this.masteredSentences, sentenceIndex]
        }
      }
    },

    // 加载句子掌握进度
    async loadSentenceProgress() {
      try {
        // 检查必要的参数是否存在
        if (!this.lesson || !this.lesson.id || !this.lesson.courseId) {
          console.warn('Lesson ID or Course ID is not available')
          return
        }

        const response = await http.get(
          `/progress/sentences?lesson_id=${this.lesson.id}&course_id=${this.lesson.courseId}`
        )
        this.masteredSentences = response
          .filter((progress) => progress.is_mastered)
          .map((progress) => progress.sentence_id)
      } catch (err) {
        console.warn('Failed to load sentence progress:', err)
      }
    }
  }
}
